package com.belf.console.service.impl;

import belf.migrate.training.LLMQueryTool;
import com.alibaba.fastjson2.JSONObject;
import com.belf.common.core.domain.AjaxResult;
import com.belf.console.domain.*;
import com.belf.console.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static com.belf.common.core.domain.AjaxResult.DATA_TAG;

@Slf4j
@Service
public class GenerateSourceDataServiceImpl implements IGenerateSourceDataService {


    @Autowired
    private IDataSourceInfoService dataSourceInfoService;

    @Autowired
    private IDataSqlTaskService dataSqlTaskService;

    @Autowired
    private IDataTaskConfService dataTaskConfService;

    @Autowired
    private IGenerateDataInfoService generateDataInfoService;

    @Autowired
    private IGenerateDataSqlService generateDataSqlService;

    @Override
    public void generate(GenerateDataModel dataModel) {

        DataSourceInfo source = dataSourceInfoService.selectDataSourceInfoById(dataModel.getSourceId());
        DataSourceInfo sink = dataSourceInfoService.selectDataSourceInfoById(dataModel.getSourceId());
        List<String> sqls = LLMQueryTool.query("Doubao-lite-32k", dataModel.getPrompt());

        int status = 0;
        List<GenerateDataSql> sqlList = new ArrayList<>();
        int index = 0;
        for (String sql : sqls) {
            if (sql.toUpperCase(Locale.ROOT).contains("CREATE SCHEMA")) {
                continue;
            }
            DataSqlTask dataSqlTask = new DataSqlTask();
            dataSqlTask.setDatasourceId(source.getId());
            dataSqlTask.setSqlContext(sql);
            AjaxResult ajaxResult = dataSqlTaskService.executeSql(dataSqlTask);
            GenerateDataSql generateDataSql = new GenerateDataSql();
            generateDataSql.setSqlContent(sql);
            generateDataSql.setStatus(0);
            generateDataSql.setMessage("执行成功");
            if (ajaxResult.isSuccess()) {
                JSONObject jsonObject = JSONObject.parseObject(ajaxResult.get(DATA_TAG).toString());
                if (jsonObject.getInteger("code") != 200) {
                    status = 1;
                    generateDataSql.setMessage(jsonObject.getString("message"));
                    generateDataSql.setStatus(1);
                }
            }
            index++;
            generateDataSql.setSort(index);
            sqlList.add(generateDataSql);
        }
        GenerateDataInfo dataInfo = new GenerateDataInfo();
        dataInfo.setSourceId(dataModel.getSourceId());
        dataInfo.setSinkId(dataModel.getSinkId());
        dataInfo.setSourceName(source.getDataSourceName());
        dataInfo.setSinkName(sink.getDataSourceName());
        dataInfo.setPrompt(dataModel.getPrompt());
        dataInfo.setLLMModel(dataModel.getLLMModel());
        dataInfo.setStatus(status);
        generateDataInfoService.insertGenerateDataInfo(dataInfo);
        int dataInfoId = dataInfo.getId();
        List<GenerateDataSql> temp = new ArrayList<>();
        for (GenerateDataSql generateDataSql : sqlList) {
            generateDataSql.setDataInfoId(dataInfoId);
            temp.add(generateDataSql);
            generateDataSqlService.batchInsertSql(temp, false);
        }
        generateDataSqlService.batchInsertSql(temp, true);
    }

    @Override
    public void createTask(GenerateDataModel dataInfo) {
        DataSourceInfo soourceDataSourceInfo = dataSourceInfoService.selectDataSourceInfoById(dataInfo.getSourceId());
        DataSourceInfo sinkDataSourceInfo = dataSourceInfoService.selectDataSourceInfoById(dataInfo.getSinkId());
        DataTaskConf dataTaskConf = new DataTaskConf();
        dataTaskConf.setTaskName("执行测试-2");
        String taskType = String.format("%s-%s", soourceDataSourceInfo.getType(), sinkDataSourceInfo.getType());
        dataTaskConf.setTaskType(taskType);
        dataTaskConf.setReaderBatch(1000L);
        /** 同步策略 1=只创建不执行,2=创建后执行 */
        dataTaskConf.setStrategy(2L);
        dataTaskConf.setTaskPolicy("ERROR_CONTINUE");
        dataTaskConf.setJobMode("ONCE");
        dataTaskConf.setJobType("SYNC_STRUCTURE");

        /**
         *  数据源配置，根据添加的数据源ID 和 数据库名称，
         */
        dataTaskConf.setSourceId(dataInfo.getSourceId());
        dataTaskConf.setSourceName(soourceDataSourceInfo.getDataSourceName());
        dataTaskConf.setSourceDatabase(soourceDataSourceInfo.getDatabaseName());
        dataTaskConf.setSourceDataSchema(soourceDataSourceInfo.getSchemaName());

        dataTaskConf.setSinkId(sinkDataSourceInfo.getId());
        dataTaskConf.setSinkName(sinkDataSourceInfo.getDataSourceName());
        dataTaskConf.setSinkDataSchema(sinkDataSourceInfo.getDatabaseName());
        dataTaskConf.setSinkDataSchema(sinkDataSourceInfo.getSchemaName());

        /**
         *  高级参数配置，没有配置不影响业务流程
         */
        dataTaskConf.setMonitorStatus(0);
        dataTaskConf.setSyncStatus(0);
        dataTaskConf.setBatchStatus(0);
        dataTaskConf.setTypeStatus(0);
        dataTaskConf.setTaskTypeScope("CREATE_TABLE,CREATE_VIEW,CREATE_FUNCTION,CREATE_TRIGGER,CREATE_PROCEDURE");

        /**  调度器 状态配置  "0=正常,1=暂停")  */
        dataTaskConf.setMonitorStatus(1);
        int i = dataTaskConfService.insertDataTaskConf(dataTaskConf);
        Long id = dataTaskConf.getId();
        System.out.println("添加成功:"+id);
    }
}
